package com.peas.platform.common.core.dto;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.peas.platform.common.core.constant.Constants;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;

@Data
public class ResponseDto<T> implements Serializable {

    private static final long serialVersionUID = 2992769554516491987L;

    @ApiModelProperty("返回码(000:成功，999:未知错误，998:登录超时)")
    private String code;
    @ApiModelProperty("错误消息")
    private String message;
    @ApiModelProperty("请求ID")
    private String requestId;
    @ApiModelProperty("耗时(毫秒)")
    private Long duration;
    @ApiModelProperty("返回数据")
    private T data;
    @ApiModelProperty("调试")
    private String debug;

    public ResponseDto() {
        this(null, null, null);
    }

    public ResponseDto(String code, String message, T data) {
        this(code, message, null, data);
    }

    public ResponseDto(String code, String message, String requestId, T data) {
        this(code, message, requestId, 0L, data);
    }

    public ResponseDto(String code, String message, String requestId, Long duration, T data) {
        this(code, message, requestId, 0L, data, null);
    }

    public ResponseDto(String code, String message, String requestId, Long duration, T data, Throwable throwable) {
        this.code = code;
        this.message = message;
        this.requestId = requestId;
        this.data = data;
        if (throwable != null) {
            this.debug = ExceptionUtil.stacktraceToOneLineString(throwable);
        }
    }

    public static <T> ResponseDto<T> getSuccessResponseDto(T data) {
        return getSuccessResponseDto(null, data);
    }

    public static <T> ResponseDto<T> getSuccessResponseDto(String requestId, T data) {
        return getSuccessResponseDto(0L, requestId, data);
    }

    public static <T> ResponseDto<T> getSuccessResponseDto(Long duration, String requestId, T data) {
        ResponseDto<T> result = new ResponseDto<>();
        result.setCode(Constants.SUCCESS_CODE);
        result.setMessage(Constants.SUCCESS_MESSAGE);
        result.setRequestId(requestId);
        result.setDuration(duration);
        result.setData(data);
        result.setDebug(null);
        return result;
    }

}
